package com.health.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.health.mail.MailSenderInfo;
import com.health.mail.SimpleMailSender;
import com.health.model.User;
import com.health.service.UserService;
import com.health.service.impl.UserServiceImpl;

public class UserManagedBean {
	private static Log log = LogFactory.getLog(UserManagedBean.class);
	//1:userlogin succeed 0:fail 2:adminlogin succeed
	private int loginFlag = 0;								//对应于loginCheck;里的flag,在此定义为成员变量是为了传给页面js调用判断
	//用户注册Vo
	private User insertVo = new User();		
	//查看详细Vo,登陆Vo
	private User user = new User();		
	//查询列表的查询条件Vo
	private User searchVo = new User();						
	//查询列表list
	private List<User> userList = new ArrayList<User>();	

	UserService service = new UserServiceImpl();			
	//send email
	MailSenderInfo mailInfo = MailSenderInfo.getInstance();			
	//在jsp页面中 : String path = request.getContextPath();
	private String path = FacesContext.getCurrentInstance().getExternalContext().getRequestContextPath();
	//是否有人登陆			>1:有   0:没有 	2:admin
	private String isAnyLoginedFlag;
	//user-list页面,每条用户记录前的选择框
	private HashMap<String,Boolean> selectMap = new HashMap<String,Boolean>();
	//选中记录(user)的条数
	private int selectCount;
	//是否更新成功		1-succeed 0-failed
	private String updateFlag;
	//HttpSession
	HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
	
	/**
	 * constructors
	 * */
	public UserManagedBean() {
	}
	
	
	/**
	 * 登陆检查,与user-login.jsp交互
	 * */
	public int loginCheck() {
		//任何用户登陆成功后这个值都是1,登陆成功后再判断该用户权限
		loginFlag = service.canLogin(user);
		if(loginFlag == 1) {
			//
			List<User> list = service.selectForList(user);
			String loginUserId = list.get(0).getId();
			User loginUser = service.selectByPK(loginUserId);
			//insert the whole "user" object into session
			session.setAttribute("currentLoginInfo", loginUser);
			isAnyLoginedFlag = "1";
			if(list.get(0).getPermission() != 0) {	//if it is not a normal user
				loginFlag = 2;						//set loginFlag = 2(admin login succeed) 
			}
		}
		return loginFlag;				//2:admin login succeed    1:user login succeed   0:failed
	}
	
	/**
	 * 检查是否有人登陆
	 * isAnyLoginedFlag,这个int值表示当前登录状态  0:没人登陆	1:普通用户(权限为0)	2:权限>=1的账户
	 * */
	public String isAnyLogined() {
		//isAnyLoginedFlag
		User u = (User)session.getAttribute("currentLoginInfo");
		if(u == null) {
			log.info("----- No one logined!(session can't get 'User') -----");
			isAnyLoginedFlag = "0";
			//forward to "user-login.jsp"
			return forUserLogin();
		} else if(u.getPermission() >= 1) {	//权限>=1,则是admin
			isAnyLoginedFlag = "2";
			return "";
		}
		return "";
	}
	
	
	
	/**
	 * 清除session中的user对象
	 * */
	public void clearSession() {
		User u = (User)session.getAttribute("currentLoginInfo");
		if(u != null) {
			session.removeAttribute("currentLoginInfo");
			log.info("---- session clear ----");
		}
	}
	
    /**
	 * 已选定的用户
	 * @return
	 */
    @SuppressWarnings("unchecked")
	public List<String> getSelectListId()
	{
		List<String> ids=new ArrayList<String>();
		if(selectMap!=null&&!selectMap.isEmpty()){
			for(Iterator it=selectMap.entrySet().iterator();it.hasNext();){
				Entry s=(Entry)it.next();
				if((Boolean)s.getValue()){
					ids.add((String)s.getKey());
				}
			}
		}
		return ids;
	}
	
    
	/**
	 * 跳转
	 * forward function
	 * */
	public String forUserInsert() {
		init();
		return "user-register";
	}
	
	public String forUserList() {
		init();
		selectForList();
		return "user-list";
	}
	
	public String forUserLogin() {
		init();
		return "user-login";
	}
	
	/**
	 * invoke SERVICE METHOD
	 * */
	public void insertUser() {
		insertVo.setRegistertime(new Date());
		insertVo.setPermission(0);	//普通用户权限
		insertVo.setStatus(0);		//账户正常状态
		try {
			service.insert(insertVo);
			mailInfo.setToAddress(insertVo.getEmail());
			mailInfo.setContent(insertVo.getName() + "We wish you good health!And our website will help you!\n" +
								" Your password is " +insertVo.getPassword() + 
								"!\nThis mail can help you save your password!Please save this mail");
			log.info("----Email Sended----");
			init();
		} catch (Exception e) {
			log.error("---- 用户注册失败!Bean抛异常 ----");
			e.printStackTrace();
		}	
		//注册之后给新用户发送邮件
	      SimpleMailSender sms = new SimpleMailSender();  
	      sms.sendTextMail(mailInfo);
	}
	
	public void selectForList() {
		userList = service.selectForList(searchVo);
		searchVo = new User();	//查询结束后将searchVo置空
		init();
		return;
	}
	
	public void selectByPK() {
		String id = user.getId();
		user = service.selectByPK(id);
		return;
	}
	
	public String deleteByPK() {
		String id = user.getId();
		service.deleteByPK(id);
		return forUserList();
	}
	
	public void updateByPK() {
		//updateFlag 1:succeed 0:failed
		int updateFlagInt = service.updateByPK(user);
		updateFlag = updateFlagInt + "";//int转String
		return;
	}
	
	/**
	 * admin在user-list页面更新user
	 * pageShowUpdate
	 * */
	public void pageShowUpdate() {
		List<String> idList = getSelectListId();
		selectCount = idList.size();
		if(selectCount != 1) {
			log.warn("select the check box error -------------- " + selectCount );
			return;
		}
		user.setId(idList.get(0));
		user = service.selectByPK(user.getId());
		return;
	}
	
	/**
	 *	if no one logined, set all admins account's birthdate to TODAY
	 *  当Session判断没人登录时,更新所有admin账户
	 *  (when restart server this method will be invoked)
	 * */
	/**
	public void updateAdmin() {
		HttpSession session = (HttpSession)FacesContext.getCurrentInstance().getExternalContext().getSession(true);
		if(session.getAttribute("currentLoginInfo") == null) {
			doUpdateAdmin();
		}
	}
	public void doUpdateAdmin() {
		//select all admins account
		searchVo.setPermission(1);
		List<User> list = service.selectForList(searchVo);
		//ergodic all admin accounts遍历所有admin账户,并更新
		Iterator<User> it = list.iterator();
		while(it.hasNext()) {
			it.next().setBirthdate(new Date());
			service.updateByPK(it.next());
		}
		init();
		
	}
	*/

	
	/** INIT EVERY OBJECT */
	public void init() {

		insertVo =  																																																																																																																																																																																																																																																																																																																																		new User();
		searchVo =
		user = new User();
	}
	
	
	
	
	
	/**
	 *  getters and setters 
	 * */
	public User getInsertVo() {
		return insertVo;
	}
	public void setInsertVo(User insertVo) {
		this.insertVo = insertVo;
	}
	
	public UserService getService() {
		return service;
	}
	public void setService(UserService service) {
		this.service = service;
	}
	
	public List<User> getUserList() {
		return userList;
	}
	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	
	public User getSearchVo() {
		return searchVo;
	}
	public void setSearchVo(User searchVo) {
		this.searchVo = searchVo;
	}

	public int getLoginFlag() {
		return loginFlag;
	}
	public void setLoginFlag(int loginFlag) {
		this.loginFlag = loginFlag;
	}

	public String getPath() {
		System.out.println(path);
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}

	public MailSenderInfo getMailInfo() {
		return mailInfo;
	}

	public void setMailInfo(MailSenderInfo mailInfo) {
		this.mailInfo = mailInfo;
	}

	public String getIsAnyLoginedFlag() {
		return isAnyLoginedFlag;
	}

	public void setIsAnyLoginedFlag(String isAnyLoginedFlag) {
		this.isAnyLoginedFlag = isAnyLoginedFlag;
	}

	public static Log getLog() {
		return log;
	}

	public static void setLog(Log log) {
		UserManagedBean.log = log;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public int getSelectCount() {
		return selectCount;
	}

	public void setSelectCount(int selectCount) {
		this.selectCount = selectCount;
	}

	public String getUpdateFlag() {
		return updateFlag;
	}

	public void setUpdateFlag(String updateFlag) {
		this.updateFlag = updateFlag;
	}

	public HashMap<String, Boolean> getSelectMap() {
		return selectMap;
	}

	public void setSelectMap(HashMap<String, Boolean> selectMap) {
		this.selectMap = selectMap;
	}






	
	
}
